﻿/// <reference path="../GeneratedArtifacts/viewModel.js" />

myapp.AddEditMovement.Details_postRender = function (element, contentItem) {
    contentItem.dataBind("screen.Movement.Id", function (newValue) {
        contentItem.screen.details.displayName = "Movement (" + (newValue == null ? "New" : newValue) + ")";
    });
    contentItem.dataBind("screen.Movement.Amount", function (newValue) {
        contentItem.screen.findContentItem("Rating").isVisible = (newValue != null && newValue != 0);
        ;
    });
};

myapp.AddEditMovement.Delete_execute = function (screen) {
    screen.Movement.deleteEntity();
};

var placeHub;
myapp.AddEditMovement.created = function (screen) {
    /*new WinJs.Promise.timeout(2000).then(function () {
        debugger;
    });*/
    //default values
    /*$.ajax({
        type: 'post',
        data: {},
        url: '../web/GetUserName.ashx',
        success: function success(result) {
            screen.UserName = result; //cache user name for filtering
        }
    });*/
    if (screen.useBingMap == null) {
        screen.useBingMap = true;
    }

    if (screen.Movement.DateFrom == null) {
        var today = new Date();
        screen.Movement.DateFrom = today;
        //screen.Movement.DateTo = today;
        screen.Movement.Hours = 0;
        screen.Movement.Minutes = 0;
    }
    if (screen.Movement.SwapStatus == null) {
        screen.Movement.SwapStatus = 0;
    }

    //events
    screen.CarsFiltered.load().then(function () {
        // After data is loaded, set a default type
        if (screen.Movement.Car == null) {
            screen.Movement.Car = msls.iterate(screen.CarsFiltered.data).first();
        }
        if (screen.Movement.Place == null) {
            toastr.info('Select place');
            myapp.AddEditMovement.MoveToSwap_execute();
        }
        //screen.Movement.Favorite = msls.iterate(screen.FavoritesFiltered.data).where(function (item) {
        //    return item.Place.Id === screen.Movement.Place.Id;
        //}).first();
    });
    /*screen.PlacesFound.load().then(function () {
    });*/
    screen.addChangeListener("PlaceId", function (e) {
        if (screen.PlaceId != null && screen.PlaceId != 0) {
            myapp.activeDataWorkspace.MMC_Content.PlacesFiltered(null, null, null, screen.PlaceId).top(1).execute().then(function (result) {
                if (result.results.length > 0) {
                    screen.Movement.Place = result.results[0];
                };
            });
        }
    });
    screen.Movement.addChangeListener("DateFrom", function (e) {
        var movement = screen.Movement, contentItem = screen.findContentItem("DateFrom"),
        today = new Date();
        today.setHours(0, 0, 0, 0);
        if ((movement.details.entityState === msls.EntityState.added || movement.details.entityState === msls.EntityState.modified) &&
            contentItem.validationResults.length === 0 &&
            movement.DateFrom < today) {
            contentItem.validationResults = [new msls.ValidationResult(screen.Movement.details.properties.DateFrom, "Do you type backdating?")];
        }
    });
    screen.Movement.addChangeListener("DateTo", function (e) {
        var movement = screen.Movement, contentItem = screen.findContentItem("DateTo"),
        today = new Date();
        today.setHours(0, 0, 0, 0);
        if ((movement.details.entityState === msls.EntityState.added || movement.details.entityState === msls.EntityState.modified) &&
            contentItem.validationResults.length === 0 &&
            movement.DateTo < today) {
            contentItem.validationResults = [new msls.ValidationResult(screen.Movement.details.properties.DateTo, "Do you type backdating?")];
        }
    });
    screen.Movement.addChangeListener("Hours", function (e) {
        var movement = screen.Movement, contentItem = screen.findContentItem("Hours");
        if ((movement.details.entityState === msls.EntityState.added || movement.details.entityState === msls.EntityState.modified) &&
            contentItem.validationResults.length === 0 &&
            (movement.Hours < 0 || movement.Hours > 1000)) {
            contentItem.validationResults = [new msls.ValidationResult(screen.Movement.details.properties.Hours, "value should be in range 0-1000")];
        }
    });
    screen.Movement.addChangeListener("Minutes", function (e) {
        var movement = screen.Movement, contentItem = screen.findContentItem("Minutes");
        if ((movement.details.entityState === msls.EntityState.added || movement.details.entityState === msls.EntityState.modified)
            && contentItem.validationResults.length === 0
            && (movement.Minutes < 0 || movement.Minutes > 60)) {
            contentItem.validationResults = [new msls.ValidationResult(screen.Movement.details.properties.Minutes, "value should be in range 0-59")];
        }
    });
    screen.Movement.addChangeListener("Car", function () {
        // When the car is changed, reset the dependent place
        if (screen.Movement.Place != null) {
            screen.Movement.Place = null;
        }
    });
    screen.Movement.addChangeListener("Place", function (e) {
        //set place defult time restriction...
        SetMovementPositionOnMap(screen);
    });

    screen.Movement.addChangeListener("SwapStatus", function (e) {
        var movement = screen.Movement, contentItem = screen.findContentItem("SwapStatus");
        if ((movement.details.entityState === msls.EntityState.added || movement.details.entityState === msls.EntityState.modified)
            && movement.Swap_Movement > 0 && movement.DateTo != null
            && contentItem.validationResults.length === 0) {
            if (movement.SwapStatus == 0) {
                screen.Message = 'to [' + movement.Swap_Movement + '] Sorry I am not ready to swap with you';
            }
            else if (movement.SwapStatus == 1) {
                screen.Message = 'to [' + movement.Swap_Movement + '] I am ready to swap with you at '
                    + formatTime(movement.DateTo);
            }
            else if (movement.SwapStatus == 2) {
                screen.Message = 'to [' + movement.Swap_Movement + '] I would like to propose swap with you at '
                    + formatTime(movement.DateTo);
            }
            else if (movement.SwapStatus == 3) {
                screen.Message = 'to [' + movement.Swap_Movement + '] I am happy to accept your time';
            }
            else if (movement.SwapStatus == 10) {
                screen.Message = 'to [' + movement.Swap_Movement + '] Thank you, I confirm swap with you at '
                    + formatTime(movement.DateTo);
            }
        }
    });
    screen.Movement.addChangeListener("Swap_Movement", function (e) {
        var movement = screen.Movement;//, contentItem = screen.findContentItem("Movement_Swap_Movement");
        if (movement.SwapStatus == 0) {
            movement.SwapStatus = 1;
        }
        if ((movement.details.entityState === msls.EntityState.added || movement.details.entityState === msls.EntityState.modified)
            //&& contentItem.validationResults.length === 0
                && movement.Car != null
            //&& movement.Place != null
            //&& (movement.SwapMovement == null || (movement.SwapMovement != null && movement.SwapMovement.Id != movement.Swap_Movement))
            ) {
            //movement.SwapMovement.load();
            movement.getSwapMovement();

            /*myapp.activeDataWorkspace.MMC_Content.SwapMovementsFiltered(movement.Swap_Movement, movement.Id, movement.Car.Id)
                .execute().then(function (results) {
                    results.forEach(function (swapMovement) {
                        movement.SwapMovement = swapMovement;
                    });
                });*/
        }
    });

    /*screen.Movement.addChangeListener("SwapMovement", function () {
        // When the swap movement is changed, update swap car
        if (screen.Movement.SwapMovement != null) {
            screen.Movement.SwapCar = screen.Movement.SwapMovement.Car;
        }
    });*/

    //screen.FavoritesFiltered.addChangeListener("selectedItem", function () {
    //    // When the swap movement is changed, update swap car
    //});

    placeHub = $.connection.placeHub;
    placeHub.client.addMessage = function (message) {
        if ($messageHistory != null) {
            $messageHistory.prepend($('<li/>').append(message));
            //setTimeout(function () {
            //    screen.movementUpdates = "";
            //}, 5000);
            toastr.info(message);
        }
    };
    $.connection.hub.start().done(function () {
        if (placeHub != null && screen.Movement.Place != null && screen.Movement.Place.Id > 0) {
            myPlace = screen.Movement.Place;
            placeHub.server.join(myPlace.Id);
            $.ajax({
                type: 'get',
                data: {
                    Longitude: myPlace.Longitude, //138,
                    Latitude: myPlace.Latitude, // - 35,
                    MaxDistance: 1000,//screen.MaxDistnace
                    MaxCount: 100, //screen.MaxCount
                    MaxPrice: screen.Movement.Amount, //screen.MaxPrice
                    MaxHours: screen.Movement.Hours, //screen.MaxHours
                    MaxMinutes: screen.Movement.Minutes, //screen.MaxMinutes
                    Date: screen.Movement.DateTo,
                    Occupied: true //request occupied places only to be able to chat
                },
                url: '../api/Places',
                success: function (response) {
                    //placesList.get(0).options.length = 0;
                    //placesList.get(0).options[0] = new Option("Select Place", "");
                    $.each(response, function (index, item) {
                        //if (myPlace.Id != item.Id) { //other swapper could be on my place as well, do not restrict by place Id
                            placeHub.server.join(item.Id);
                            //placesList.get(0).options[index + 1] = new Option(item.Id, item.Distance);
                        //}
                    });
                }
            });
        }
    }).fail(function () {
        alert("Could not connect to places hub");
    });
};

var googleMapDiv;
myapp.AddEditMovement.googleMap_render = function (element, contentItem) {
    googleMapDiv = $('<div id="gmap_canvas" style="width: 100%; height: 100%" />').appendTo($(element)); //class="gmap3" 
    $(googleMapDiv).lightswitchGoogleMapsControl();
};

var bingMapDiv;
myapp.AddEditMovement.bingMap_render = function (element, contentItem) {
    bingMapDiv = $('<div id="bmap_canvas" style="width: 100%; height: 100%" />').appendTo($(element));
    $(bingMapDiv).lightswitchBingMapsControl();
    $(bingMapDiv).lightswitchBingMapsControl("resetMap");
};

myapp.AddEditMovement.useBingMap_render = function (element, contentItem) {
    createMapSwitch(element, contentItem, 'Bing', 'Google', '10em');
};

myapp.AddEditMovement.DrivingMode_render = function (element, contentItem) {
    createBooleanSwitch(element, contentItem, 'Walking', 'Driving', '', '10em');
};

myapp.AddEditMovement.TrafficMode_render = function (element, contentItem) {
    createBooleanSwitch(element, contentItem, 'Show', 'Hide', '', '10em');
};
//myapp.AddEditMovement.testTraffic_execute = function (screen) {
//    $(bingMapDiv).lightswitchBingMapsControl("testTraffic", screen);
//};

//var directionsItineraryDiv;
myapp.AddEditMovement.directionsItinerary_render = function (element, contentItem) {
    var directionsItineraryDiv = $('<div id="directionsItinerary"></div>').appendTo($(element)); //style="border : width : 200px; height : 50px; "
    /*var directionsItineraryDiv = $('#directionsItinerary');
    if (directionsItineraryDiv != null) {
        $(this).remove();
    }*/
};
/*
myapp.AddEditMovement.FavoritesFiltered_ItemTap_execute = function (screen) {
    if (screen.FavoritesFiltered.selectedItem != null && screen.FavoritesFiltered.selectedItem.Place != null) {
        screen.Movement.Place = screen.FavoritesFiltered.selectedItem.Place;
    }
};
*/

/*
var audioPlayer;
function PlaySound() {
    if (audioPlayer == null) {
        audioPlayer = $('<audio autoplay controls preload="auto" autobuffer><source src="Content/Audio/Bubble.m4a" type="audio/aac"></audio>')
            .appendTo($('#defaultCountdown'));
    }
    
    //audioPlayer = $('<div id="jquery_jplayer_1"></div><div id="jp_container_1"> <a href="#" class="jp-play">Play</a> <a href="#" class="jp-pause">Pause</a></div>').appendTo($(element));
    //$("#alarm")[0].play();
    //sound.load();
    //sound.play();
    //var path = $(location).attr('href') + "Content/Audio/ALARM.WAV";
    ////alert(path);
    //var snd = new Audio(path); // buffers automatically when created
    //snd.play();
    //snd.play();
    //snd.play();
}
*/

myapp.AddEditMovement.DateTo_postRender = function (element, contentItem) {
    //contentItem.dataBind("value", function (newValue) {
    //    RefreshCountDown(newValue);
    //});
};

//use dataBind with a render or postRender function, this allows to easily get notified when some property has changed
//, regardless of how deeply nested tha data is
//use addChangeListener within Entity and Screen functions. This code would work anyware you show the data (avoiding the need to
//duplicate the logic on each screen the data objects appear on)

myapp.AddEditMovement.Hours_postRender = function (element, contentItem) {
    contentItem.dataBind("value", function (newValue) {
        var newDateTo = new Date(contentItem.screen.Movement.DateFrom.getTime() + newValue * 60 * 60000 + contentItem.screen.Movement.Minutes * 60000);
        if (contentItem.screen.Movement.DateTo == null || (contentItem.screen.Movement.DateTo != null && contentItem.screen.Movement.DateTo.getTime() != newDateTo.getTime())) {
            contentItem.screen.Movement.DateTo = newDateTo;
        }
    });
};

myapp.AddEditMovement.Minutes_postRender = function (element, contentItem) {
    contentItem.dataBind("value", function (newValue) {
        var newDateTo = new Date(contentItem.screen.Movement.DateFrom.getTime() + contentItem.screen.Movement.Hours * 60 * 60000 + newValue * 60000);
        if (contentItem.screen.Movement.DateTo == null || (contentItem.screen.Movement.DateTo != null && contentItem.screen.Movement.DateTo.getTime() != newDateTo.getTime())) {
            contentItem.screen.Movement.DateTo = newDateTo;
        }
    });
};

myapp.AddEditMovement.DateFrom_postRender = function (element, contentItem) {
    contentItem.dataBind("value", function (newValue) {
        var newDateTo = new Date(newValue.getTime() + contentItem.screen.Movement.Hours * 60 * 60000 + contentItem.screen.Movement.Minutes * 60000);
        if (contentItem.screen.Movement.DateTo == null || (contentItem.screen.Movement.DateTo != null && contentItem.screen.Movement.DateTo.getTime() != newDateTo.getTime())) {
            contentItem.screen.Movement.DateTo = newDateTo;
        }
    });
};


var $messageHistory;
myapp.AddEditMovement.MessageHistory_render = function (element, contentItem) {
    // Write code here.
    $messageHistory = $('<ul style="list-style: none;"/>').appendTo(element);
};


myapp.AddEditMovement.SendMessage_canExecute = function (screen) {
    return (screen.Movement.Id != null);

};
myapp.AddEditMovement.SendMessage_execute = function (screen) {
    if (screen.Movement.Place == null) {
        alert("please select place before sending message");
        return;
        //var contentItem = screen.findContentItem("Message");
        //contentItem.validationResults = [new msls.ValidationResult(screen.Message, "please select place before sending message")];
    }
    var myDate = new Date();
    if (placeHub != null) {
        placeHub.server.sendToGroup(screen.Movement.Place.Id, '[' + screen.Movement.Id + '] ' + formatTime(myDate) + ': ' + screen.Message);
        screen.Message = "";
    }
};

myapp.AddEditMovement.RouteFromHereToPlace_canExecute = function (screen) {
    return (screen.Movement.Place != null);
};
myapp.AddEditMovement.RouteFromHereToPlace_execute = function (screen) {
    if (screen.Movement.Place && navigator && navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(function (position) {
            var fromPlace = { Address: "Current Position", Latitude: position.coords.latitude, Longitude: position.coords.longitude };
            var toPlace = { Address: screen.Movement.Place.Address, Latitude: screen.Movement.Place.Latitude, Longitude: screen.Movement.Place.Longitude, Draggable: false };
            if (screen.useBingMap) {
                $(bingMapDiv).lightswitchBingMapsControl("createMovementRoute", fromPlace, toPlace, screen.DrivingMode, screen.TrafficMode);
            }
            else {
                $(googleMapDiv).lightswitchGoogleMapsControl("createMovementRoute", fromPlace, toPlace, screen.DrivingMode, screen.TrafficMode);
            }
            //screen.showPopup("ShowDirectionsItinerary");
        }, geo_error);
    }
    else {
        alert("Geolocation is not supported/allowed by this browser.");
    }
};

myapp.AddEditMovement.RouteFromPlaceToSwap_canExecute = function (screen) {
    // Write code here.
    return (screen.Movement.SwapMovement != null);

};
myapp.AddEditMovement.RouteFromPlaceToSwap_execute = function (screen) {
    if (screen.Movement.Place && screen.Movement.SwapMovement && screen.Movement.SwapMovement.Place) {
        var fromPlace = screen.Movement.Place;
        var toPlace = screen.Movement.SwapMovement.Place;
        if (screen.useBingMap) {
            $(bingMapDiv).lightswitchBingMapsControl("createMovementRoute", fromPlace, toPlace, screen.DrivingMode, screen.TrafficMode);
        }
        else {
            $(googleMapDiv).lightswitchGoogleMapsControl("createMovementRoute", fromPlace, toPlace, screen.DrivingMode, screen.TrafficMode);
        }
        //screen.showPopup("ShowDirectionsItinerary");
    }
};

myapp.AddEditMovement.Map_postRender = function (element, contentItem) {
    //var movement = contentItem.screen.Movement;
    SetMovementPositionOnMap(contentItem.screen);
};

myapp.AddEditMovement.AddPlaceToFavorites_canExecute = function (screen) {
    return (screen.Movement.Place != null);
};
myapp.AddEditMovement.AddPlaceToFavorites_execute = function (screen) {
    if (screen.Movement.Place != null) {
        var found = msls.iterate(screen.FavoritesFiltered.data).where(function (item) {
            return item.Place.Id === screen.Movement.Place.Id;
        }).first();
        if (!found) {
            var newFavorites = myapp.activeDataWorkspace.MMC_Content.Favorites.addNew();
            newFavorites.Car = screen.Movement.Car;
            newFavorites.Place = screen.Movement.Place;
            myapp.activeDataWorkspace.MMC_Content.saveChanges().then(function () {
                // Refresh the Favorites
                screen.getFavoritesFiltered();
            });
        }
    }
};


myapp.AddEditMovement.MoveToSwap_canExecute = function (screen) {
    // Write code here.

};
myapp.AddEditMovement.MoveToSwap_execute = function (screen) {
    if (screen.Movement.SwapMovement != null) {
        myapp.activeDataWorkspace.MMC_Content.MovementsFiltered(screen.Movement.SwapMovement.Place_Movement, screen.Movement.Car.Id, screen.Movement.DateTo.setMinutes(screen.Movement.DateTo.getMinutes() + 10))
            .execute().then(function (results) {
                if (results.totalCount == 0) {
                    var newMovement = myapp.activeDataWorkspace.MMC_Content.Movements.addNew();
                    newMovement.Car = screen.Movement.Car;
                    newMovement.Place = screen.Movement.SwapMovement.Place;
                    newMovement.DateFrom = screen.Movement.DateTo;
                    newMovement.Hours = screen.Movement.Hours;
                    newMovement.Minutes = screen.Movement.Minutes;
                    var newDateTo = new Date(newMovement.DateFrom.getTime() + newMovement.Hours * 60 * 60000 + newMovement.Minutes * 60000);
                    newMovement.DateTo = newDateTo;
                    myapp.activeDataWorkspace.MMC_Content.saveChanges();
                    //myapp.applyChanges();
                }
            });
    }
};


myapp.AddEditMovement.ShowFindPlace_execute = function (screen) {
    // Write code here.
    myapp.showFindPlace({
        beforeShown: function (findPlaceScreen) {
            findPlaceScreen.PlaceId = (screen.Movement.Place != null ? screen.Movement.Place.Id : null);
            findPlaceScreen.CarId = (screen.Movement.Car != null ? screen.Movement.Car.Id : null);
            findPlaceScreen.PlaceIsShared = screen.PlaceIsShared;
            findPlaceScreen.PlaceLocation = screen.PlaceLocation;
        },
        afterClosed: function (findPlaceScreen, navigationAction) {
            // If the user commits the change, update PlaceId in movement screen.
            if (navigationAction === msls.NavigateBackAction.commit) {
                screen.PlaceId = findPlaceScreen.PlaceId;
            }
        }
    });
};

function SetMovementPositionOnMap(screen) {
    var place = screen.Movement.Place;
    if (place != null) {
        var movementPlace = { Address: place.Address, Latitude: place.Latitude, Longitude: place.Longitude, Draggable: false };
        if (movementPlace.Latitude != null && movementPlace.Longitude != null) {
            if (screen.useBingMap) {
                $(bingMapDiv).lightswitchBingMapsControl("getCurrentPosition", movementPlace);
            }
            else {
                $(googleMapDiv).lightswitchGoogleMapsControl("getCurrentPosition", movementPlace);
            }
        }
        else if (plamovementPlacece.Address != null && movementPlace.Address != "") {
            if (screen.useBingMap) {
                $(bingMapDiv).lightswitchBingMapsControl("getPositionByAddress", movementPlace);
            }
            else {
                $(googleMapDiv).lightswitchGoogleMapsControl("getPositionByAddress", movementPlace);
            }
        }
    }
};

myapp.AddEditMovement.beforeApplyChanges = function (screen) {
    // Write code here.

};
